from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from apps.goods.models import SKUImage
from apps.meiduo_admin.serializers.image import ImageSkuModelSerializer
from apps.meiduo_admin.utils import PageNum
from rest_framework.generics import ListAPIView
from apps.goods.models import SKU
from apps.meiduo_admin.serializers.image import SimpleSKUViewSerializer
from fdfs_client.client import Fdfs_client
from rest_framework import status


class ImageSkuViewSet(ModelViewSet):

    pagination_class = PageNum
    queryset = SKUImage.objects.all()
    serializer_class = ImageSkuModelSerializer

    # 重写create方法，因为系统的create方法不能将数据保存到数据库中
    def create(self, request, *args, **kwargs):
        fdfs_client = Fdfs_client('utils/fastdfs/client.conf')
        # 接受数据
        image = request.FILES.get('image')
        if not image:
            return Response(status=status.HTTP_403_FORBIDDEN)
        # 如文件存在则通过客户端上传文件
        res = fdfs_client.upload_appender_by_buffer(image.read())
        if res['Status'] != 'Upload successed.':
            return Response(status=status.HTTP_403_FORBIDDEN)
        # 获取sku_id值
        sku_id = request.data.get('sku')
        # 将返回的数据内容保存到数据中
        data = SKUImage.objects.create(sku_id=sku_id, image=res.get('Remote file_id'))
        # 返回数据
        return Response(
            {
                'id': data.id,
                'sku': sku_id,
                'image': data.image.url
            },
            status=201
        )




class SimpleSKUView(ListAPIView):

    queryset = SKU.objects.all()
    serializer_class = SimpleSKUViewSerializer
